from django.contrib.auth.models import User
from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response

from .models import Profile
from .serializers import ProfileSerializer,ResetPassSerializer,LoginSerializer
from drf_spectacular.utils import extend_schema


@extend_schema(
    tags=['Account']
)
class ProfileViewSet(viewsets.GenericViewSet): # 没有和model进行关联,就用通用的 GenericViewSet

    @extend_schema(
        request=LoginSerializer,
        responses=ProfileSerializer
    )
    @action(methods=["POST"], detail=False)
    def login(self,request): # 登录
        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)  # 委托给序列化进行参数校验

        profile = Profile.objects.get(user=serializer.validated_data['user'])
        serializer = ProfileSerializer(profile)
        return Response(serializer.data)  # 委托给序列化进行字段和数据生成

    @extend_schema(
        request=ResetPassSerializer,
        responses={204:None}
    )
    @action(methods=["POST"], detail=False)
    def reset_password(self,request): # 重置密码
        serializer = ResetPassSerializer(data=request.data)
        serializer.is_valid(raise_exception=True) # 委托给序列化进行参数校验

        user: User = request.user
        user.set_password(serializer.validated_data['new_password'])
        user.save()
        return Response({},status=status.HTTP_204_NO_CONTENT)

    @extend_schema(
        responses=ProfileSerializer
    )
    @action(methods=["GET"], detail=False)
    def profile(self,request): # 查询个人资料
        profile = Profile.objects.get(user=request.user)

        serializer = ProfileSerializer(profile)
        return Response(serializer.data)  # 委托给序列化进行字段和数据生成

    @extend_schema(
        request=ProfileSerializer,
        responses=ProfileSerializer
    )
    @action(methods=["POST"], detail=False)
    def change(self,request): # 修改个人资料
        profile = Profile.objects.get(user=request.user)

        serializer = ProfileSerializer(profile,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save() # 将请求数据和models数据进行合并，然后保存

        return Response(serializer.data)  # 委托给序列化进行字段和数据生成
